package com.bcbim.api_model.sys.init.code;

import com.bcbim.authentication_interface.code.po.SysCode;
import com.bcbim.authentication_interface.code.service.SysCodeService;
import com.bcbim.common.sys.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Description: 初始化系统内码值映射
 * @Author haoshuai
 * @Date 2020/9/22
 * @Version V1.0
 **/
@Slf4j
@Component
@Order(1)
public class InitCodeMap implements CommandLineRunner {

    @Reference(protocol = "dubbo", group = "sysCode", version = "1.0.0")
    private SysCodeService sysCodeServiceImpl;

    @Override
    public void run(String... args) throws Exception {

        log.info("Starting initialization code map");

        List<SysCode> list = sysCodeServiceImpl.getAllSysCode();

        //获取码值类class
        Class<CodeMap> clazz = CodeMap.class;

        //组装码值
        assemblyCodeMap(CodeMap.CODE_MAPPING, list, clazz);

        log.info("Starting initialization code map success");

    }

    /**
     * @Description: 组装码值
     * @Param: Map<String, String> codeMapping
     * @Param: List<SysCode> list
     * @Param: Class<?> c
     * @Author: haoshuai
     * @Date: 2020/8/27
     */
    private void assemblyCodeMap(Map<String, String> map,
                                 List<SysCode> list,
                                 Class<?> c) throws IllegalAccessException, InstantiationException, NoSuchFieldException {
        //获取实例
        Object obj = c.newInstance();
        //组装码值对
        for (SysCode o : list) {
            String codeType = map.get(o.getType());
            if(StringUtils.isEmpty(codeType))
                continue;
            String mapName = codeType.replace(Constant.TYPE_SUFFIX, Constant.MAP_SUFFIX);
            Map<String, String> codeMap =
                    (Map<String, String>) c.getField(mapName).get(null);
            codeMap.put(o.getCode(), o.getName());
            c.getField(mapName).set(obj, codeMap);
        }
    }

}
